package com.csx.data.routing.multids.datasource;

import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.util.Objects;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2023/10/20 周五 15:33
 */
public class DynamicDataSource extends AbstractDataSourceProxy implements Closeable {

    private volatile DataSource target;

    public DynamicDataSource(DataSource target) {
        this.target = target;
    }

    public synchronized DataSource replaceTarget(DataSource target) {
        Objects.requireNonNull(target, "目标数据源不能为null");
        DataSource old = this.target;
        this.target = target;
        return old;
    }

    @Override
    protected DataSource chooseDataSource() {
        return target;
    }


    @Override
    public void close() throws IOException {
        if(target instanceof Closeable) {
            ((Closeable) target).close();
        }
    }
}
